package leetcode_题库;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 *
 * @ProjectName leetcode
 * @Author Ding
 * @CreateTime 2022/8/30 9:30 星期二
 */
public class _653_两数之和2_输入二叉搜索树 {

    /**
     * 把list换成set，成功了
     * > 2022/08/30 09:45:20
     * 解答成功:
     * 	执行耗时:6 ms,击败了12.66% 的Java用户
     * 	内存消耗:42.3 MB,击败了23.40% 的Java用户
     * @param root
     * @param k
     * @return
     */
    public boolean findTarget_ok(TreeNode root, int k) {
        if (root == null) {
            return false;
        }

        Deque<TreeNode> stack = new ArrayDeque<>();
        HashSet<Integer> set = new HashSet<>();
        stack.add(root);
        TreeNode cur = root;

        while (!stack.isEmpty()) {
            if (cur != null) {
                stack.push(cur);
                cur = cur.left;
            } else {
                TreeNode pre = stack.pop();
                set.add(pre.val);
                if (pre.right != null) {
                    stack.push(pre.right);
                    cur = pre.right.left;
                }
            }
        }
        for (Integer integer : set) {
            if (set.contains(k-integer) && k-integer != integer){
                return true;
            }
        }
        return false;
    }

    //直接超时，md
    public boolean findTarget(TreeNode root, int k) {
        if (root == null) {
            return false;
        }
        Deque<TreeNode> stack = new ArrayDeque<>();
        List<Integer> list = new ArrayList<>();
        stack.add(root);
        TreeNode cur = root;

        while (!stack.isEmpty()) {
            if (cur != null) {
                stack.push(cur);
                cur = cur.left;
            } else {
                TreeNode pre = stack.pop();
                list.add(pre.val);
                if (pre.right != null) {
                    stack.push(pre.right);
                    cur = pre.right.left;
                }
            }
        }

        int p1 = 0;
        int p2 = list.size() - 1;
        while (p1 < p2) {
            if (list.get(p1) + list.get(p2) == k) {
                return true;
            }
        }

        return false;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
